import {baseEffects, baseReducers, baseState} from "../../../../models/baseModel";
import moment from "moment";
import * as request from "../../../../services/CommonHttpService";
import $$ from 'utils';

export default {
  namespace: 'datachart',

  state: {
    ...baseState,
    deviceInfo: {},
    chartData: [],
    uploadStatistics: [],
  },

  reducers: {
    ...baseReducers
  },

  effects: {

    ...baseEffects,

    * getData({payload}, {put, call}) {

      let {filters, errorMsg, notice, server} = payload;

      if (!!filters) {
        const time = !!filters.time ? filters.time : [];
        if (time.length == 2) {
          const startTime = !!time[0] && time[0].format('x');
          const endTime = !!time[1] && time[1].format('x');
          if (!!startTime && !!endTime)
            filters = {...filters, startTime, endTime};
        }

        delete filters.time;
        console.log(filters);
        $$.removeNullItem(filters);
      }

      try {
        const data = [];
        let result = yield call(request.commonGet, "/data/chart-data", {}, {...filters}, server);
        for (let i = 0; i < result.length; i++) {
          data.push({
            // year: moment(result[i].time).format("YYYY-MM-DD HH:mm:ss"),
            time: result[i].time,
            value: Number(result[i].result)
          });
        }

        yield put({
          type: 'initState',
          payload: {chartData: data}
        });
      } catch (error) {
        console.error("getData", error);
        yield put({type: 'loadError'});
        !!notice && notice("error", !!errorMsg ? errorMsg : error);
      }
    },

  }

}

function getBaseUrl() {
  return "/device";
}

